<template>
	<div class="overflow-hidden">
		<n-card :bordered="false" class="h-full rounded-8px shadow-sm">
			<div class="flex-col h-full">

				<div class=" w-full  ">
					<n-space class="pb-12px flex-items-center" justify="space-between">
						<n-space class="flex-items-center">
							<n-button type="primary" @click="handleAddTable">
								<icon-ic-round-plus class="mr-4px text-20px" />
								新增
							</n-button>
							<n-button type="primary" @click="syncSeckill">
								<icon-mdi-refresh class="mr-4px text-20px" />
								同步
							</n-button>
							过滤已结束
							<n-switch v-model:value="active" @update:value="filterChange">
								<template #checked>
									已过滤
								</template>
								<template #unchecked>
									未过滤
								</template>
							</n-switch>
						</n-space>
						<n-space align="center" :size="18">
							<n-button size="small" type="primary" @click="getTableData">
								<icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
								刷新表格
							</n-button>
							<column-setting v-model:columns="columns" />
						</n-space>
					</n-space>
				</div>
				<div class="h-full  flex">
					<n-data-table :columns="columns" :data="tableData" :loading="loading" :pagination="pagination" size="small"
						:single-line="false" flex-height class="flex-1" />
					<table-action-modal v-model:visible="visible" :type="modalType" :edit-data="editData"
						@on-confirm="() => { getTableData(); }" />
					<sync-iqiyi-seckill v-model:visible="visibleSync" @on-confirm="() => { getTableData(); }" />
				</div>
			</div>
		</n-card>
	</div>
</template>

<script setup lang="tsx">
import { reactive, ref } from "vue";
import type { Ref } from "vue";
import { NButton, NPopconfirm, NSpace, NTag } from "naive-ui";
import type { DataTableColumns, PaginationProps } from "naive-ui";
import { fetchIqiyi, DelIQIYISeckill } from "@/service";
import { useBoolean, useLoading } from "@/hooks";
import ColumnSetting from "../../component/table/column-setting.vue";
import TableActionModal from "./components/table-action-modal.vue";
import SyncIqiyiSeckill from "./components/sync-seckill.vue";
import type { ModalType } from "./components/table-action-modal.vue";

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();
const { bool: visibleSync, setTrue: openSyncModal } = useBoolean();

const tableData = ref<Seckill.IQIYISeckill[]>([]);

const active = ref<boolean>(true);

function setTableData(data: Seckill.IQIYISeckill[]) {
	tableData.value = data;
}
async function getTableData() {
	startLoading();
	let startTime = null;
	if (active.value) {
		// 计算一个小时之前的小时数
		var previousHour = new Date().getHours() - 1;
		// 创建一个新的 Date 对象，设置为一个小时之前的时间
		startTime = new Date();
		startTime.setHours(previousHour);
	}
	let input: Seckill.GetIQIYISeckillInput = {
		startTime: startTime,
		endTime: null
	};
	const { data } = await fetchIqiyi(input);
	if (data) {
		pagination.itemCount = data.length;
		setTableData(data);
		endLoading();
	}
}

const columns: Ref<DataTableColumns<Seckill.IQIYISeckill>> = ref([
	{
		type: "selection",
		align: "center",
	},
	{
		key: "index",
		title: "序号",
		align: "center",
		width: 80,
		render: (_, index) => {
			return `${index + 1}`
		}
	},
	{
		key: "name",
		title: "活动名称",
		align: "left",
	},
	{
		key: "seckillTime",
		title: "秒杀时间",
		align: "center",
		width: 200,
	}, {
		key: "status",
		title: "秒杀状态",
		align: "center",
		render: (row) => {
			if (row.seckillTime) {
				let tagType: NaiveUI.ThemeColor = "success";
				let msg = "未开始";
				let sTime = new Date(row.seckillTime);
				let eTime = new Date(new Date(row.seckillTime).setHours(new Date(row.seckillTime).getHours() + 1));
				if (new Date() < sTime) {
					tagType = "info";
					msg = "未开始";
				} else if (new Date() > eTime) {
					tagType = "error";
					msg = "已结束";
				}
				else {
					tagType = "success";
					msg = "进行中";
				}
				return (
					<NTag type={tagType}>
						{msg}
					</NTag>
				);
			}
			return <span></span>;
		},
		width: 100,
	},
	{
		key: "code",
		title: "商品代码",
		align: "center",
		width: 200,
	},
	{
		key: "lastModifiedTime",
		title: "最后更新时间",
		align: "center",
		width: 200,
	},
	{
		key: "actions",
		title: "操作",
		align: "center",
		width: 200,
		render: (row) => {
			return (
				<NSpace justify={"center"}>
					<NButton size={"small"} onClick={() => handleEditTable(row.id)}>
						编辑
					</NButton>
					<NPopconfirm onPositiveClick={() => handleDeleteTable(row.id)}>
						{{
							default: () => "确认删除",
							trigger: () => <NButton size={"small"}>删除</NButton>,
						}}
					</NPopconfirm>
				</NSpace>
			);
		},
	},
]) as Ref<DataTableColumns<Seckill.IQIYISeckill>>;

const editData = ref<Seckill.IQIYISeckill | null>(null);

function setEditData(data: Seckill.IQIYISeckill | null) {
	editData.value = data;
}

async function filterChange(value: boolean) {
	await getTableData();
}
const modalType = ref<ModalType>("add");

function setModalType(type: ModalType) {
	modalType.value = type;
}


function handleAddTable() {
	openModal();
	setModalType("add");
	setEditData(null);
}

function handleEditTable(rowId: number) {
	const findItem = tableData.value.find((item) => item.id === rowId);
	if (findItem) {
		setEditData(findItem);
	}
	setModalType("edit");
	openModal();
}

async function handleDeleteTable(rowId: number) {
	await DelIQIYISeckill(rowId);
	window.$message?.success(`删除成功`);
	await getTableData();
}

async function syncSeckill() {
	openSyncModal();
}
const pagination: PaginationProps = reactive({
	page: 1,
	pageSize: 20,
	showSizePicker: true,
	pageSizes: [20, 30, 50, 100],
	prefix: (pagingInfo) => `共 ${pagingInfo.itemCount} 条`,
	onChange: (page: number) => {
		pagination.page = page;
	},
	onUpdatePageSize: (pageSize: number) => {
		pagination.pageSize = pageSize;
		pagination.page = 1;
	},
});

function init() {
	getTableData();
}

// 初始化
init();
</script>

<style scoped></style>
